/**
 * Copyright 2018-2020 stylefeng & fengshuonan (https://gitee.com/stylefeng)
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.stylefeng.guns.sys.core.util;

import cn.stylefeng.roses.core.util.ToolUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.util.List;

/**
 * 缓存工具类
 */
@Slf4j
public class FileUtils {



    /**
     * @Author
     * @Description 文件上传
     * @Date 2019/7/31  15:48
     * @Param [file, filePath, fileName]
     * @return void
     **/
    public static Boolean uploadFile(byte[] file, String filePath, String fileName) throws Exception {
        FileOutputStream out = null;
        try {
            File targetFile = new File(filePath);
            //如果目录不存在，创建目录
            if(!targetFile.exists()){
                targetFile.mkdirs();
            }
            out = new FileOutputStream(filePath+fileName);
            out.write(file);
            out.flush();
            //写入成功
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            //写入失败
            return false;
        } finally {
            out.close();
        }
    }

    /**
     * 数据写入到文件
     * @param path
     * @param fileName
     * @param list 数据
     * @return
     */
    public static boolean write2File(String path,String fileName, List<String> list) throws Exception {
        if(ToolUtil.isEmpty(path)){
            path="/";//默认取根目录
        }
        if(ToolUtil.isEmpty(fileName)){
            fileName=DateUtil.getStampNow()+".txt";//默认取当前时间戳
        }
        File parent = new File(path);
        if(!parent.exists()){
            parent.mkdirs();
        }
        File target = new File(path,fileName);
        if(!target.exists()){
            target.createNewFile();
        }
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(target),"UTF-8"));
        for(String str:list){
            StringBuffer sb = new StringBuffer();
            sb.append(str);
            bw.write(sb.toString());
            bw.newLine();
        }
        bw.flush();
        bw.close();
        return true;
    }

}


